package cn.gaoyu.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.task.TaskExecutor;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.ThreadPoolExecutor;

/**
 * @author: GaoYu
 * @date: 2025/2/5
 * @description: <p>异步的线程池</p>
 * @version: 1.0.0
 */
@Slf4j
@Configuration
@ConditionalOnProperty(prefix = "platform.async", name = "enable", havingValue = "true", matchIfMissing = false)
public class AsyncThreadPoolConfig {
    /**
     * 线程池维护线程的最小数量.
     */
    @Value("${platform.async.corePoolSize:10}")
    private int corePoolSize;
    /**
     * 线程池维护线程的最大数量
     */
    @Value("${platform.async.maxPoolSize:200}")
    private int maxPoolSize;
    /**
     * 队列最大长度
     */
    @Value("${platform.async.queueCapacity:1000}")
    private int queueCapacity;
    /**
     * 线程池前缀
     */
    @Value("${platform.async.threadNamePrefix:async-}")
    private String threadNamePrefix;

    @Bean("asyncTaskExecutor")
    public TaskExecutor taskExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(corePoolSize);
        executor.setMaxPoolSize(maxPoolSize);
        executor.setQueueCapacity(queueCapacity);
        executor.setThreadNamePrefix(threadNamePrefix);
        /*
           rejection-policy：当pool已经达到max size的时候，如何处理新任务
           CALLER_RUNS：不在新线程中执行任务，而是有调用者所在的线程来执行
        */
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        executor.initialize();
        log.info("[异步任务初始化线程池]\nBean名称:asyncTaskExecutor\n核心线程数: {}\n最大线程数: {}\n队列最大数量: {}\n线程池前缀: {}",
                corePoolSize, maxPoolSize, queueCapacity, threadNamePrefix);
        return executor;
    }
}
